package com.imooc.course.server.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.course.server.dao.CourseContentDao;
import com.imooc.course.server.dto.CourseContentDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.entity.CourseContent;
import com.imooc.course.server.entity.CourseContentExample;
import com.imooc.course.server.service.CourseContentService;
import com.imooc.course.server.utils.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;

@Service("courseContentService")
public class CourseContentServiceImpl implements CourseContentService {

    private static final Logger log = LoggerFactory.getLogger(CourseContentServiceImpl.class);

    @Resource(name = "courseContentDao")
    private CourseContentDao courseContentDao;

    /**
     * 列表查询
     * @param pageDto
     */
    @Override
    public void getList(PageDto pageDto) {
        PageHelper.startPage(pageDto.getPage(),pageDto.getSize());

        CourseContentExample courseContentExample = new CourseContentExample();
        List<CourseContent> courseContentList = courseContentDao.selectByExample(courseContentExample);

        PageInfo<CourseContent> courseContentPageInfo = new PageInfo<>(courseContentList);
        pageDto.setTotal(courseContentPageInfo.getTotal());

        List<CourseContentDto> courseContentDtoList = CopyUtil.copyList(courseContentList, CourseContentDto.class);

        pageDto.setList(courseContentDtoList);
    }

    @Override
    public CourseContentDto getByCourseId(String courseId) {
        CourseContent courseContent = courseContentDao.selectByPrimaryKey(courseId);
        if (courseContent == null) {
            return null;
        }
        return CopyUtil.copy(courseContent, CourseContentDto.class);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param courseContentDto
     */
    @Override
    public void save(CourseContentDto courseContentDto) {
        CourseContent copy = CopyUtil.copy(courseContentDto, CourseContent.class);
        String id = courseContentDto.getId() != null ? courseContentDto.getId().trim() : courseContentDto.getId();
        if (StringUtils.isEmpty(id)) {
            this.addCourseContent(copy);
        }else{
            this.modifyCourseContent(copy);
        }
    }

    @Override
    public int modifyCourseContent(CourseContent courseContent) {
        //当数据表中有大字段时，就会生成withBLOBs方法
        return courseContentDao.updateByPrimaryKeyWithBLOBs(courseContent);
    }

    @Override
    public int addCourseContent(CourseContent courseContent) {
        return courseContentDao.insertSelective(courseContent);
    }

    /**
     * 删除
     * @param id
     */
    @Override
    public void delete(String id) {
        courseContentDao.deleteByPrimaryKey(id);
    }
}
